import router from "@/router";
import { Box3, Box3Helper, Camera, Raycaster, Vector2, Vector3, WebGLRenderer, type AnimationClip, type Group, type Mesh, type Object3DEventMap, type Scene } from "three";
import { GLTFLoader } from "three/examples/jsm/Addons.js"
import type { Object3D } from "three/src/Three.WebGPU.Nodes.js";

interface LoadelFallback {
  model: Group<Object3DEventMap>
  animations: AnimationClip[]
}


export const loadGO2Model = (scene: Scene, camera: Camera, renderer: WebGLRenderer) => {
  const loader = new GLTFLoader();
  let model: Group<Object3DEventMap>;

  const keysPressed: { [key: string]: boolean } = {};
  const moveSpeed = 0.1; // 每帧移动速度，可以调整


  loader.load("/models/GO2_EDU.gltf", (gltf) => {

    model = gltf.scene
    const animations = gltf.animations

    model.traverse((node) => {
      if ((node as Mesh).isMesh) {
        node.castShadow = true // 设置阴影

      }
    })

    let box = new Box3().setFromObject(model);
    const boxHelper = new Box3Helper(box, 0xffff00);
    const center = new Vector3();
    const size = new Vector3();
    box.getCenter(center); // 获取中心点
    box.getSize(size); // 获取模型尺寸

    // console.log("center", center);
    // console.log("size", size);

    model.add(boxHelper)
    model.scale.set(3, 3, 3)

    // 旋转模型
    model.rotation.x = -Math.PI / 2

    // // 使用模型尺寸偏移，置于ground
    model.position.y = size.y / 2 + -(0 - size.y); // 身体+头部
    model.position.z = size.z / 1.5;

    box = new Box3().setFromObject(model)
    box.getCenter(center)

    scene.add(gltf.scene)


    // 添加键盘事件监听器
    window.addEventListener('keydown', onKeyDown);
    window.addEventListener('keyup', onKeyUp);

    // 动画循环中处理移动
    function animate() {
      if (!model) return;

      // WASD 控制
      if (keysPressed['w'] || keysPressed['W']) {
        model.position.z += moveSpeed; // 前进
      }
      if (keysPressed['s'] || keysPressed['S']) {
        model.position.z -= moveSpeed; // 后退
      }
      if (keysPressed['a'] || keysPressed['A']) {
        model.position.x += moveSpeed; // 左移
      }
      if (keysPressed['d'] || keysPressed['D']) {
        model.position.x -= moveSpeed; // 右移
      }

      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }
    animate();

  })


  const onKeyDown = (event: KeyboardEvent) => {
    keysPressed[event.key] = true;
  }

  const onKeyUp = (event: KeyboardEvent) => {
    keysPressed[event.key] = false;
  }


  return () => {
    window.removeEventListener('keydown', onKeyDown);
    window.removeEventListener('keyup', onKeyUp);
  };
}


